package teaching.io.temp;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;

import teaching.io.entity.Student;

/**
 * 随机访问存取对象信息示例。
 * 
 * @author deng.zhao
 *
 */
public class TextFileExample {

	public static void writeStudents(List<Student> students) {
		try (BufferedWriter bw = new BufferedWriter(new FileWriter("d:/stu.txt", true));) {
			for (Student student : students) {
				writeStudent(bw, student);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static void writeStudent(BufferedWriter bw, Student student) throws IOException {
		GregorianCalendar calendar = new GregorianCalendar();
		calendar.setTime(student.getBirthDate());
		String str = String.format("%s,%s,%d-%d-%d,%c", student.getId(), student.getName(), calendar.get(Calendar.YEAR),
				calendar.get(Calendar.MONTH), calendar.get(Calendar.DATE), student.getGender());
		bw.write(str);
		bw.newLine();
	}

	public static List<Student> readStudents() {
		List<Student> students = new ArrayList<Student>();

		try (BufferedReader br = new BufferedReader(new FileReader("d:/stu.txt"));) {
			Student stu = null;
			while ((stu = readStudent(br)) != null) {
				students.add(stu);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return students;
	}

	public static Student readStudent(BufferedReader br) throws IOException {
		String str = br.readLine();
		if (str != null) {
			// 处理数据；
			String[] fields = str.split(",");
			Student stu = new Student();
			stu.setId(fields[0]);
			stu.setName(fields[1]);
			stu.setGender(fields[3].charAt(0));

			// 处理日期；
			String[] dateInfo = fields[2].split("-");
			GregorianCalendar calender = new GregorianCalendar();
			calender.set(Integer.parseInt(dateInfo[0]), Integer.parseInt(dateInfo[1]), Integer.parseInt(dateInfo[2]));
			stu.setBirthDate(calender.getTime());

			return stu;
		} else {
			return null;
		}
	}

	public static void main(String[] args) {
		// 写入测试；
		List<Student> students = new ArrayList<Student>();
		students.add(new Student("0001", "张三", new GregorianCalendar(1997, Calendar.JANUARY, 28).getTime(), 'M'));
		students.add(new Student("0002", "李四", new GregorianCalendar(1996, Calendar.DECEMBER, 7).getTime(), 'F'));
		students.add(new Student("0003", "王五", new GregorianCalendar(1997, Calendar.DECEMBER, 20).getTime(), 'F'));
		writeStudents(students);

		// 读出测试；
		for (Student student : readStudents()) {
			System.out.println(student);
		}

	}
}
